package cn.hsp.twocolorball;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

/**
 * 厦门大学计算机专业 | 前华为工程师
 * 专注《零基础学编程系列》https://cxyxy.blog.csdn.net/article/details/121134634
 * 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 * 公众号：蓝不蓝编程
 */
public class HspActivity extends AppCompatActivity {
    private final int interval = 50;
    private final Handler handler = new Handler(Looper.getMainLooper());
    private final BallNumUtil ballNumUtil = new BallNumUtil();
    private View startIv;
    private View pauseIv;
    private TextView firstBallTv;
    private TextView secondBallTv;
    private TextView thirdBallTv;
    private TextView fourthBallTv;
    private TextView fifthBallTv;
    private TextView sixthBallTv;
    private TextView seventhBallTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hsp);
        startIv = findViewById(R.id.startIv);
        pauseIv = findViewById(R.id.pauseIv);
        firstBallTv = findViewById(R.id.firstBallTv);
        secondBallTv = findViewById(R.id.secondBallTv);
        thirdBallTv = findViewById(R.id.thirdBallTv);
        fourthBallTv = findViewById(R.id.fourthBallTv);
        fifthBallTv = findViewById(R.id.fifthBallTv);
        sixthBallTv = findViewById(R.id.sixthBallTv);
        seventhBallTv = findViewById(R.id.seventhBallTv);

        startIv.setOnClickListener(v -> startTimer());
        pauseIv.setOnClickListener(v -> stopTimer());
    }

    private void startTimer() {
        handler.postDelayed(this::changeBalls, interval);
        showPauseBtn();
    }

    private void stopTimer() {
        handler.removeCallbacksAndMessages(null);
        showStartBtn();
    }

    private void changeBalls() {
        firstBallTv.setText(ballNumUtil.getRedBallNum());
        secondBallTv.setText(ballNumUtil.getRedBallNum());
        thirdBallTv.setText(ballNumUtil.getRedBallNum());
        fourthBallTv.setText(ballNumUtil.getRedBallNum());
        fifthBallTv.setText(ballNumUtil.getRedBallNum());
        sixthBallTv.setText(ballNumUtil.getRedBallNum());
        seventhBallTv.setText(ballNumUtil.getBlueBallNum());
        handler.postDelayed(this::changeBalls, interval);
    }

    private void showStartBtn() {
        startIv.setVisibility(View.VISIBLE);
        pauseIv.setVisibility(View.GONE);
    }

    private void showPauseBtn() {
        startIv.setVisibility(View.GONE);
        pauseIv.setVisibility(View.VISIBLE);
    }

}